package com.jxsd.edu.cn.struts2.NET;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class IPCatcher {

	/**
	 * 通过有道服务获取用户ip所在位置
	 * @return inputStream
	 */
	public InputStream youdaoIPService() throws Exception {
		String netPath = "http://www.youdao.com/smartresult-xml/search.s?type=ip&q=202.101.194.216";
		URL url = new URL(netPath);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		return connection.getInputStream();
	}

	/**
	 * 通过InputStream产生xml文件
	 * @param file_name
	 * @param is
	 */
	public void file_put_contents(String file_name, InputStream is) {
		File file = new File(file_name);
		OutputStream os = null;
		try {
			os = new FileOutputStream(file);
			byte buffer[] = new byte[4 * 1024];
			int len = 0;
			while ((len = is.read(buffer)) != -1)
			{
				os.write(buffer, 0, len);
			}
			os.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				os.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 将InputStream转换为字符串
	 */
	public String InputStreamToString(InputStream inputStream) throws Exception{
		String allIPData="";
		String str;
		BufferedReader  br=new BufferedReader(new InputStreamReader(inputStream, "GBK"));
		str=br.readLine();
		while(str!=null){
			str=br.readLine();
			if(str!=null){
				allIPData=allIPData+str;
			}
		}
		inputStream.close();
		return allIPData;
	}
	
	
	

	
	/**
	 * 开始进行location进行匹配
	 * @param str
	 * @return
	 */
	public static List getContext(String str) {
        List resultList = new ArrayList();
        Pattern p = Pattern.compile("<location>([^</location>]*)");//匹配<location>开头，</location>结尾的文档
        Matcher m = p.matcher(str );//开始编译
        while (m.find()) {
            resultList.add(m.group(1));//获取被匹配的部分
        }
        return resultList;
    }
	
	/**
	 * 开始进行location进行匹配
	 * @param str
	 * @return
	 */
	public static String getCity(String str){
		List resultList = getContext(str);
		String city="";
        for (Iterator iterator = resultList.iterator(); iterator.hasNext();) {
            city = (String) iterator.next();
        }
		return city;
	}
	
	public static String convertFromGBKToUTF8(String  str,String  toType){
		String  to=null;
		   byte[]  b=str.getBytes();
		   try {
			to=new  String(b,toType);
		} catch (Exception e) 
		{
			e.printStackTrace();
		}
		   return  to;
	}

}
